package com.myapp.web.tomcat;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import org.apache.catalina.Lifecycle;
import org.apache.catalina.LifecycleEvent;
import org.apache.catalina.LifecycleListener;

public class MailDeamonProcessor implements LifecycleListener {

    //protected ArrayList listeners = new ArrayList();
    
    private Thread thread = null;
    
    protected int backgroundProcessorDelay = 1;
    
    protected BlockingQueue taskQueue = new LinkedBlockingQueue();
    
    private boolean threadDone = false;
	
	protected void threadStart(){
		if (thread != null)
            return;

        threadDone = false;
        String threadName = "MailBackgroundProcessor";
        thread = new Thread(new MailBackgroundProcessor(), threadName);
        thread.setDaemon(true);
        thread.start();		
	}
	
	protected void threadStop() {
		if (thread == null)
		       return;

        threadDone = true;
        thread.interrupt();
        try {
            thread.join();
        } catch (InterruptedException e) {
            ;
        }
        thread = null;
	}
		
	class MailBackgroundProcessor implements Runnable{

		@Override
		public void run() {
			System.out.println("MailBackgroundProcessor start to run.....");
			while (!threadDone) {
                try {
                	Object task = taskQueue.take();
                } catch (InterruptedException e) {
                    ;
                }
                if (!threadDone){
                	System.out.println("MailBackgroundProcessor running.....");
                }
			}
		}		
	}

	@Override
	public void lifecycleEvent(LifecycleEvent event) {
        if (Lifecycle.START_EVENT.equals(event.getType())) {
        	threadStart();
        } else if (Lifecycle.STOP_EVENT.equals(event.getType())) {
        	threadStop();
        }		
	}
}
